<template>
  <div class="profile-page">
    <div class="page-header">
      <h1>个人资料</h1>
      <p>管理您的个人信息和账户设置</p>
    </div>

    <div class="profile-content">
      <div class="profile-card">
        <div class="profile-avatar-section">
          <div class="avatar-container">
            <img :src="profile.avatar" :alt="profile.name" class="profile-avatar" />
            <button class="avatar-edit-btn" @click="changeAvatar">
              <i class="icon-camera"></i>
            </button>
          </div>
          <div class="avatar-info">
            <h2 class="profile-name">{{ profile.name }}</h2>
            <p class="profile-role">{{ profile.role }}</p>
            <div class="profile-status">
              <span class="status-indicator" :class="profile.status"></span>
              <span class="status-text">{{ getStatusText(profile.status) }}</span>
            </div>
          </div>
        </div>

        <div class="profile-form">
          <div class="form-section">
            <h3 class="section-title">基本信息</h3>
            
            <div class="form-row">
              <div class="form-group">
                <label class="form-label">姓名</label>
                <input 
                  v-model="profile.name" 
                  type="text" 
                  class="form-input"
                  :disabled="!isEditing"
                />
              </div>
              
              <div class="form-group">
                <label class="form-label">职位</label>
                <input 
                  v-model="profile.role" 
                  type="text" 
                  class="form-input"
                  :disabled="!isEditing"
                />
              </div>
            </div>

            <div class="form-row">
              <div class="form-group">
                <label class="form-label">邮箱</label>
                <input 
                  v-model="profile.email" 
                  type="email" 
                  class="form-input"
                  :disabled="!isEditing"
                />
              </div>
              
              <div class="form-group">
                <label class="form-label">电话</label>
                <input 
                  v-model="profile.phone" 
                  type="tel" 
                  class="form-input"
                  :disabled="!isEditing"
                />
              </div>
            </div>

            <div class="form-group">
              <label class="form-label">部门</label>
              <select v-model="profile.department" class="form-input" :disabled="!isEditing">
                <option value="customer-service">客服部</option>
                <option value="sales">销售部</option>
                <option value="technical">技术部</option>
                <option value="management">管理层</option>
              </select>
            </div>

            <div class="form-group">
              <label class="form-label">个人简介</label>
              <textarea 
                v-model="profile.bio" 
                class="form-textarea"
                :disabled="!isEditing"
                rows="4"
                placeholder="介绍一下自己..."
              ></textarea>
            </div>
          </div>

          <div class="form-section">
            <h3 class="section-title">工作偏好</h3>
            
            <div class="form-group">
              <label class="form-label">工作时间</label>
              <div class="time-range">
                <input 
                  v-model="profile.workHours.start" 
                  type="time" 
                  class="form-input"
                  :disabled="!isEditing"
                />
                <span class="time-separator">至</span>
                <input 
                  v-model="profile.workHours.end" 
                  type="time" 
                  class="form-input"
                  :disabled="!isEditing"
                />
              </div>
            </div>

            <div class="form-group">
              <label class="form-label">专长领域</label>
              <div class="skills-container">
                <span 
                  v-for="skill in profile.skills" 
                  :key="skill"
                  class="skill-tag"
                >
                  {{ skill }}
                  <button 
                    v-if="isEditing" 
                    @click="removeSkill(skill)"
                    class="skill-remove"
                  >
                    ×
                  </button>
                </span>
                <input 
                  v-if="isEditing"
                  v-model="newSkill"
                  @keyup.enter="addSkill"
                  type="text" 
                  placeholder="添加专长..."
                  class="skill-input"
                />
              </div>
            </div>
          </div>

          <div class="form-section">
            <h3 class="section-title">统计信息</h3>
            
            <div class="stats-grid">
              <div class="stat-item">
                <div class="stat-value">{{ profile.stats.totalChats }}</div>
                <div class="stat-label">总聊天数</div>
              </div>
              <div class="stat-item">
                <div class="stat-value">{{ profile.stats.avgResponseTime }}</div>
                <div class="stat-label">平均响应时间</div>
              </div>
              <div class="stat-item">
                <div class="stat-value">{{ profile.stats.satisfactionRate }}%</div>
                <div class="stat-label">满意度</div>
              </div>
              <div class="stat-item">
                <div class="stat-value">{{ formatDate(profile.joinDate) }}</div>
                <div class="stat-label">加入时间</div>
              </div>
            </div>
          </div>

          <div class="form-actions">
            <button 
              v-if="!isEditing" 
              @click="startEdit" 
              class="btn btn-primary"
            >
              <i class="icon-edit"></i>
              <span>编辑资料</span>
            </button>
            
            <template v-else>
              <button @click="saveProfile" class="btn btn-primary" :disabled="saving">
                <i v-if="saving" class="icon-loading spinning"></i>
                <i v-else class="icon-save"></i>
                <span>{{ saving ? '保存中...' : '保存' }}</span>
              </button>
              <button @click="cancelEdit" class="btn btn-secondary">
                <i class="icon-cancel"></i>
                <span>取消</span>
              </button>
            </template>
          </div>
        </div>
      </div>
    </div>

    <!-- 头像上传（隐藏） -->
    <input 
      ref="avatarInput" 
      type="file" 
      accept="image/*"
      @change="handleAvatarChange"
      style="display: none"
    />
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'

const isEditing = ref(false)
const saving = ref(false)
const newSkill = ref('')
const avatarInput = ref()

// 个人资料数据
const profile = reactive({
  name: '客服小王',
  role: '高级客服专员',
  email: 'xiaowang@company.com',
  phone: '138-0000-0000',
  department: 'customer-service',
  bio: '专注于为客户提供优质的服务体验，擅长处理各类技术问题和产品咨询。',
  avatar: '/default-avatar.png',
  status: 'online',
  workHours: {
    start: '09:00',
    end: '18:00'
  },
  skills: ['产品咨询', '技术支持', '投诉处理', '客户关系'],
  stats: {
    totalChats: 1248,
    avgResponseTime: '2.5分钟',
    satisfactionRate: 96,
  },
  joinDate: new Date('2023-03-15')
})

// 备份原始数据
let originalProfile = null

const getStatusText = (status) => {
  const statusMap = {
    online: '在线',
    away: '离开',
    busy: '忙碌',
    offline: '离线'
  }
  return statusMap[status] || '未知'
}

const formatDate = (date) => {
  return date.toLocaleDateString('zh-CN')
}

const startEdit = () => {
  originalProfile = JSON.parse(JSON.stringify(profile))
  isEditing.value = true
}

const cancelEdit = () => {
  if (originalProfile) {
    Object.assign(profile, originalProfile)
    originalProfile = null
  }
  isEditing.value = false
}

const saveProfile = async () => {
  saving.value = true
  
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 这里应该调用实际的API
    console.log('保存个人资料:', profile)
    
    isEditing.value = false
    originalProfile = null
    
    // 显示成功消息
    alert('个人资料已保存')
    
  } catch (error) {
    console.error('保存失败:', error)
    alert('保存失败，请重试')
  } finally {
    saving.value = false
  }
}

const changeAvatar = () => {
  avatarInput.value?.click()
}

const handleAvatarChange = (event) => {
  const file = event.target.files?.[0]
  if (!file) return

  // 检查文件类型
  if (!file.type.startsWith('image/')) {
    alert('请选择图片文件')
    return
  }

  // 检查文件大小（限制为2MB）
  if (file.size > 2 * 1024 * 1024) {
    alert('图片大小不能超过2MB')
    return
  }

  // 创建预览
  const reader = new FileReader()
  reader.onload = (e) => {
    profile.avatar = e.target?.result
  }
  reader.readAsDataURL(file)
}

const addSkill = () => {
  if (newSkill.value.trim() && !profile.skills.includes(newSkill.value.trim())) {
    profile.skills.push(newSkill.value.trim())
    newSkill.value = ''
  }
}

const removeSkill = (skill) => {
  const index = profile.skills.indexOf(skill)
  if (index > -1) {
    profile.skills.splice(index, 1)
  }
}
</script>

<style scoped>
.profile-page {
  padding: var(--spacing-xl);
  max-width: 800px;
  margin: 0 auto;
}

.page-header {
  text-align: center;
  margin-bottom: var(--spacing-xl);
}

.page-header h1 {
  margin-bottom: var(--spacing-md);
  font-size: var(--font-size-2xl);
  color: var(--color-text);
}

.page-header p {
  color: var(--color-text-secondary);
  font-size: var(--font-size-lg);
}

.profile-card {
  background: var(--color-surface);
  border: 1px solid var(--color-border);
  border-radius: var(--border-radius-xl);
  overflow: hidden;
}

.profile-avatar-section {
  display: flex;
  align-items: center;
  gap: var(--spacing-xl);
  padding: var(--spacing-xl);
  background: linear-gradient(135deg, var(--color-primary) 0%, var(--color-primary-dark) 100%);
  color: white;
}

.avatar-container {
  position: relative;
}

.profile-avatar {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  object-fit: cover;
  border: 4px solid rgba(255, 255, 255, 0.2);
}

.avatar-edit-btn {
  position: absolute;
  bottom: 0;
  right: 0;
  width: 32px;
  height: 32px;
  background: var(--color-primary-dark);
  color: white;
  border: 2px solid white;
  border-radius: 50%;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all var(--transition-fast);
}

.avatar-edit-btn:hover {
  background: var(--color-primary);
  transform: scale(1.1);
}

.profile-name {
  margin-bottom: var(--spacing-sm);
  font-size: var(--font-size-xl);
  font-weight: var(--font-weight-bold);
}

.profile-role {
  margin-bottom: var(--spacing-md);
  font-size: var(--font-size-base);
  opacity: 0.9;
}

.profile-status {
  display: flex;
  align-items: center;
  gap: var(--spacing-sm);
}

.status-indicator {
  width: 12px;
  height: 12px;
  border-radius: 50%;
}

.status-indicator.online {
  background: var(--color-success);
}

.status-indicator.away {
  background: var(--color-warning);
}

.status-indicator.busy {
  background: var(--color-error);
}

.status-indicator.offline {
  background: var(--color-text-secondary);
}

.profile-form {
  padding: var(--spacing-xl);
}

.form-section {
  margin-bottom: var(--spacing-xl);
}

.section-title {
  margin-bottom: var(--spacing-lg);
  font-size: var(--font-size-lg);
  font-weight: var(--font-weight-semibold);
  color: var(--color-text);
  padding-bottom: var(--spacing-md);
  border-bottom: 1px solid var(--color-border);
}

.form-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: var(--spacing-lg);
}

.form-group {
  margin-bottom: var(--spacing-lg);
}

.form-label {
  display: block;
  margin-bottom: var(--spacing-sm);
  font-size: var(--font-size-sm);
  font-weight: var(--font-weight-medium);
  color: var(--color-text);
}

.form-input,
.form-textarea {
  width: 100%;
  padding: var(--spacing-md);
  border: 1px solid var(--color-border);
  border-radius: var(--border-radius-md);
  background: var(--color-background);
  color: var(--color-text);
  font-size: var(--font-size-base);
  transition: border-color var(--transition-fast);
}

.form-input:focus,
.form-textarea:focus {
  outline: none;
  border-color: var(--color-primary);
}

.form-input:disabled,
.form-textarea:disabled {
  background: var(--color-surface);
  color: var(--color-text-secondary);
  cursor: not-allowed;
}

.time-range {
  display: flex;
  align-items: center;
  gap: var(--spacing-md);
}

.time-separator {
  color: var(--color-text-secondary);
}

.skills-container {
  display: flex;
  flex-wrap: wrap;
  gap: var(--spacing-sm);
  align-items: center;
}

.skill-tag {
  display: inline-flex;
  align-items: center;
  gap: var(--spacing-xs);
  padding: var(--spacing-xs) var(--spacing-sm);
  background: var(--color-primary-alpha);
  color: var(--color-primary);
  font-size: var(--font-size-sm);
  border-radius: var(--border-radius-full);
  font-weight: var(--font-weight-medium);
}

.skill-remove {
  background: none;
  border: none;
  color: var(--color-primary);
  cursor: pointer;
  font-size: 16px;
  line-height: 1;
  padding: 0;
  margin-left: var(--spacing-xs);
}

.skill-input {
  flex: 1;
  min-width: 120px;
  padding: var(--spacing-xs) var(--spacing-sm);
  border: 1px dashed var(--color-border);
  border-radius: var(--border-radius-md);
  background: transparent;
  font-size: var(--font-size-sm);
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  gap: var(--spacing-lg);
}

.stat-item {
  text-align: center;
  padding: var(--spacing-lg);
  background: var(--color-background);
  border-radius: var(--border-radius-lg);
  border: 1px solid var(--color-border);
}

.stat-value {
  font-size: var(--font-size-xl);
  font-weight: var(--font-weight-bold);
  color: var(--color-primary);
  margin-bottom: var(--spacing-sm);
}

.stat-label {
  font-size: var(--font-size-sm);
  color: var(--color-text-secondary);
}

.form-actions {
  display: flex;
  gap: var(--spacing-md);
  justify-content: center;
  padding-top: var(--spacing-xl);
  border-top: 1px solid var(--color-border);
}

.btn {
  display: inline-flex;
  align-items: center;
  gap: var(--spacing-sm);
  padding: var(--spacing-md) var(--spacing-xl);
  border: 1px solid transparent;
  border-radius: var(--border-radius-md);
  font-size: var(--font-size-base);
  font-weight: var(--font-weight-medium);
  cursor: pointer;
  transition: all var(--transition-fast);
  text-decoration: none;
}

.btn-primary {
  background: var(--color-primary);
  color: var(--color-text-inverse);
  border-color: var(--color-primary);
}

.btn-primary:hover:not(:disabled) {
  background: var(--color-primary-dark);
  border-color: var(--color-primary-dark);
}

.btn-primary:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.btn-secondary {
  background: var(--color-surface);
  color: var(--color-text);
  border-color: var(--color-border);
}

.btn-secondary:hover {
  background: var(--color-hover);
  border-color: var(--color-border-dark);
}

.spinning {
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

/* 图标样式 */
.icon-camera::before { content: '📷'; }
.icon-edit::before { content: '✏️'; }
.icon-save::before { content: '💾'; }
.icon-cancel::before { content: '❌'; }
.icon-loading::before { content: '⟳'; }

/* 响应式设计 */
@media (max-width: 768px) {
  .profile-page {
    padding: var(--spacing-lg);
  }
  
  .profile-avatar-section {
    flex-direction: column;
    text-align: center;
  }
  
  .form-row {
    grid-template-columns: 1fr;
  }
  
  .time-range {
    flex-direction: column;
    align-items: stretch;
  }
  
  .form-actions {
    flex-direction: column;
  }
  
  .stats-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}
</style>